﻿using VIA.Integration.Domain.Production;

namespace VIA.Project.Domain.Services
{
    public class FilePathBuilder : IFilePathBuilder
    {
        /// <summary>
        /// 是否将图片按照产品OK/NG文件夹分别存储
        /// </summary>
        public bool IsUseOKNGFolder { get; set; }
        public FilePathBuilder() { }

        public string GetFileNameWithoutExtension(string root, ImageStoragePackage package)
        {
            string? time = package.Result?.StartTime.ToString("yyyy-MM-dd");
            if (string.IsNullOrEmpty(time))
            {
                time = package.Source?.Result?.StartTime.ToString("yyyy-MM-dd");
            }
            if (string.IsNullOrEmpty(time))
            {
                time = DateTime.Now.ToString("yyyy-MM-dd");
            }
            string? qlt = package.Result?.Quality.ToString().ToUpper();
            if (string.IsNullOrEmpty(qlt))
            {
                qlt = package.Source?.Result?.Quality.ToString().ToUpper();
            }
            if (string.IsNullOrEmpty(qlt))
            {
                qlt = "NG";
            }
            string folderName = package.Product.Barcode;
            string imageName = $"{package.Product.Barcode}_{qlt}";
            foreach (var item in package.Args)
            {
                imageName += $"_{item}";
            }
            imageName += $"_{DateTime.Now:HHmmssfff}";
            var cameraName = package?.Args?.FirstOrDefault(x => x.Contains("相机"));
            string filePath;
            if (!cameraName.IsNullOrEmpty())
            {
                filePath = Path.Combine(root, time, cameraName, folderName, imageName);
            }
            else
            {
                filePath = Path.Combine(root, time, folderName, imageName);
            }
            if (IsUseOKNGFolder)
                filePath = Path.Combine(root, qlt, time, folderName, imageName);
            return filePath;

        }

        public string BuildSourceImagePath(string root, ImageStoragePackage package)
        {
            var filePath = GetFileNameWithoutExtension(root, package);
            return Path.ChangeExtension(filePath, ".png");
        }

        public string BuildResultImagePath(string root, ImageStoragePackage package)
        {
            var filePath = GetFileNameWithoutExtension(root, package);
            return Path.ChangeExtension(filePath, ".jpg");
        }
    }
}
